package com.riche.codefactory.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.riche.codefactory.annotation.AuthCheck;
import com.riche.codefactory.common.BaseResponse;
import com.riche.codefactory.common.DeleteRequest;
import com.riche.codefactory.common.ErrorCode;
import com.riche.codefactory.common.R;
import com.riche.codefactory.constant.UserConstant;
import com.riche.codefactory.exception.BusinessException;
import com.riche.codefactory.exception.ThrowUtils;
import com.riche.codefactory.model.c2s.post.C2sPostAddRequest;
import com.riche.codefactory.model.c2s.post.C2sPostEditRequest;
import com.riche.codefactory.model.c2s.post.C2sPostQueryRequest;
import com.riche.codefactory.model.c2s.post.C2sPostUpdateRequest;
import com.riche.codefactory.model.domain.Post;
import com.riche.codefactory.model.domain.User;
import com.riche.codefactory.model.s2c.S2cPost;
import com.riche.codefactory.service.IPostSVC;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.riche.codefactory.service.IUserSVC;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 帖子接口
 *
 *

 */
@RestController
@RequestMapping("/post")
@Slf4j
public class PostController {

    @Resource
    private IPostSVC IPostSVC;

    @Resource
    private IUserSVC userService;

    // region 增删改查

    /**
     * 创建
     *
     * @param c2sPostAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addPost(@RequestBody C2sPostAddRequest c2sPostAddRequest, HttpServletRequest request) {
        if (c2sPostAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Post post = new Post();
        BeanUtils.copyProperties(c2sPostAddRequest, post);
        List<String> tags = c2sPostAddRequest.getTags();
        if (tags != null) {
            post.setTags(JSONUtil.toJsonStr(tags));
        }
        IPostSVC.validPost(post, true);
        User loginUser = userService.getLoginUser(request);
        post.setUserId(loginUser.getId());
        post.setFavourNum(0);
        post.setThumbNum(0);
        boolean result = IPostSVC.save(post);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newPostId = post.getId();
        return R.ok(newPostId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePost(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Post oldPost = IPostSVC.getById(id);
        ThrowUtils.throwIf(oldPost == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldPost.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = IPostSVC.removeById(id);
        return R.ok(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param c2sPostUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePost(@RequestBody C2sPostUpdateRequest c2sPostUpdateRequest) {
        if (c2sPostUpdateRequest == null || c2sPostUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Post post = new Post();
        BeanUtils.copyProperties(c2sPostUpdateRequest, post);
        List<String> tags = c2sPostUpdateRequest.getTags();
        if (tags != null) {
            post.setTags(JSONUtil.toJsonStr(tags));
        }
        // 参数校验
        IPostSVC.validPost(post, false);
        long id = c2sPostUpdateRequest.getId();
        // 判断是否存在
        Post oldPost = IPostSVC.getById(id);
        ThrowUtils.throwIf(oldPost == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = IPostSVC.updateById(post);
        return R.ok(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<S2cPost> getPostVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Post post = IPostSVC.getById(id);
        if (post == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return R.ok(IPostSVC.getPostVO(post, request));
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param c2sPostQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Post>> listPostByPage(@RequestBody C2sPostQueryRequest c2sPostQueryRequest) {
        long current = c2sPostQueryRequest.getCurrent();
        long size = c2sPostQueryRequest.getPageSize();
        Page<Post> postPage = IPostSVC.page(new Page<>(current, size),
                IPostSVC.getQueryWrapper(c2sPostQueryRequest));
        return R.ok(postPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param c2sPostQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<S2cPost>> listPostVOByPage(@RequestBody C2sPostQueryRequest c2sPostQueryRequest,
                                                        HttpServletRequest request) {
        long current = c2sPostQueryRequest.getCurrent();
        long size = c2sPostQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Post> postPage = IPostSVC.page(new Page<>(current, size),
                IPostSVC.getQueryWrapper(c2sPostQueryRequest));
        return R.ok(IPostSVC.getPostVOPage(postPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param c2sPostQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<S2cPost>> listMyPostVOByPage(@RequestBody C2sPostQueryRequest c2sPostQueryRequest,
                                                          HttpServletRequest request) {
        if (c2sPostQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        c2sPostQueryRequest.setUserId(loginUser.getId());
        long current = c2sPostQueryRequest.getCurrent();
        long size = c2sPostQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Post> postPage = IPostSVC.page(new Page<>(current, size),
                IPostSVC.getQueryWrapper(c2sPostQueryRequest));
        return R.ok(IPostSVC.getPostVOPage(postPage, request));
    }

    // endregion

    /**
     * 分页搜索（从 ES 查询，封装类）
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
//    @PostMapping("/search/page/vo")
//    public BaseResponse<Page<PostVO>> searchPostVOByPage(@RequestBody PostQueryRequest postQueryRequest,
//            HttpServletRequest request) {
//        long size = postQueryRequest.getPageSize();
//        // 限制爬虫
//        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
//        Page<Post> postPage = postService.searchFromEs(postQueryRequest);
//        return ResultUtils.ok(postService.getPostVOPage(postPage, request));
//    }

    /**
     * 编辑（用户）
     *
     * @param c2sPostEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editPost(@RequestBody C2sPostEditRequest c2sPostEditRequest, HttpServletRequest request) {
        if (c2sPostEditRequest == null || c2sPostEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Post post = new Post();
        BeanUtils.copyProperties(c2sPostEditRequest, post);
        List<String> tags = c2sPostEditRequest.getTags();
        if (tags != null) {
            post.setTags(JSONUtil.toJsonStr(tags));
        }
        // 参数校验
        IPostSVC.validPost(post, false);
        User loginUser = userService.getLoginUser(request);
        long id = c2sPostEditRequest.getId();
        // 判断是否存在
        Post oldPost = IPostSVC.getById(id);
        ThrowUtils.throwIf(oldPost == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldPost.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = IPostSVC.updateById(post);
        return R.ok(result);
    }

}
